<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="js/vue.js"></script>
    <style>
        *{
            margin: 0;
            padding: 0;
            list-style: none;
        }
        .tr{
            display: flex;
        }
        .tr  .item{
            flex: 1;
            background-color: black;
            color: aliceblue;
            text-align: center;
            line-height: 40px;
        }
    </style>
</head>
<body>
    <div id="app">

        <div>
            姓名   <input type="text" :value="username" @input="setusername"/>
             年龄  <input type="text" :value="userage" @input="setuserage"/>
             <button @click="add">新增</button>
        </div>

        <hr/>


        <div class="table">
            <div class="tr">
                    <div class="item">编号</div>
                    <div class="item">用户名</div>
                    <div class="item">年龄</div>
                    <div class="item">操作</div>
            </div>

            <div class="tr" v-for="item  in infoList">
                <div class="item">{{item.id}}</div>
                <div class="item">{{item.username}}</div>
                <div class="item">{{item.userage}}</div>
                <div class="item" @click="delById(item.id)">删除</div>
            </div>
        </div>
         
    </div>
    
</body>
<script>
    //注意  对象的解析  只有一个层 没有属性 不会报错
    //如果对象是连续点击的  就要注意 中间有没有 undefined 
    new  Vue({
        el:"#app",
        data:{
            username:"",
            userage:"",
           infoList:[{id:1,username:"leson",userage:18},{id:2,username:"lili",userage:18},{id:3,username:"lulu",userage:18}]
        },
        methods:{
            delById(id){//数组的常用方法
               this.infoList = this.infoList.filter(item=>item.id!=id); //过滤
            },
            add(){
                let id = 1;
                if(this.infoList.length){//判断集合有没有长度
                    id = this.infoList.map(item=>item.id).sort((a,b)=>b-a)[0]+1;//map取出了所有id  把id倒序   取第一个就是最大的  最大的+1
                }
                //用户名不能重复
                if(!this.infoList.some(item=>item.username==this.username)){ //表示用户名不存在
                    this.infoList.push({
                    id,
                    username:this.username,
                    userage:this.userage
                })
                }else{
                    alert(this.username+"已经存在");
                }
            },
            setusername(e){
                this.username = e.target.value;
            },
            setuserage(e){
                this.userage = e.target.value;

            }
        }
    })

</script>
</html>